package openjdk.future;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by boot on 1/11/16.
 * 线程池的使用：
 * Note : 线程池使用一定要关闭(执行 showdown()方法),会有垃圾线程，
 * 除非使用kill 命令来关闭。
 */
public class TestExecutorService {

    /**
     * 此处没有返回值，使用其实现了Runnable 接口，在实际工作中我们可能要实现
     * Callable<T> 接口，将其作为参数传FutureTask 类来实现异步返.
     */
    static class Job implements Runnable {

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            doWork();
        }

        private void doWork() {
            System.out.println("doing...");
        }
    }

    /**
     * 使用线程池将几个互不依赖的动作切分，通过多线程对串行工作改进，成倍
     * 地提高工作效率。
     *
     * @param args
     */
    public static void main(String[] args) {
        // 创建一个固定大小为5的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        // 用这个线程池并发执行10个任务
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Job());
        }
        executorService.shutdown();
    }
}
